package cn.lg.soar.redis.manager;

import cn.lg.soar.core.sn.SnElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 基于redis的流水号
 * @author luguoxiang
 * @date 2022/4/7
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Component
public class SnElementRedisSerial implements SnElement {

	@Autowired
	private RedisTemplate redisTemplate;

	@Override
	public String getKey() {
		return "redisSerial";
	}

	/**
	 * 例：redisSerial(4,$prefix,86400000)
	 * 方法说明：redisSerial(length, key, expire)
	 * @param length：流水位数
	 * @param key：redis 流水key
	 * @param expire：redis 流水有效期
	 * @return
	 */
	@Override
	public String getValue(Object... args) {
		Integer len = (Integer) args[0];
		String key = "redisSerial:" + args[1];
		Integer ex = (Integer) args[2];
		long serial = redisTemplate.opsForValue().increment(key);
		redisTemplate.expire(key, ex, TimeUnit.MILLISECONDS);
		String format = String.format("%0" + len + "d", serial);
		return format.substring(format.length() - len);
	}

}